package com.yisu.expressway.api.web.controller;

import com.alibaba.fastjson.JSON;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.Webhooks;
import com.yisu.expressway.api.core.service.IOrderService;
import com.yisu.expressway.api.domain.request.orderModule.PaySuccessRequest;
import com.yisu.expressway.api.domain.vo.pingXX.PingXXRequestObjectVo;
import com.yisu.expressway.ewf.entity.OrderMain;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created by Administrator on 2016-12-23.
 */

@Controller
@RequestMapping("/notify")
public class NotifyController {

    @Resource
    private IOrderService iOrderService;


    @RequestMapping(value = "/PingNotify", produces = "application/json; charset=utf-8")
    @ResponseBody
    public void PingNotify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF8");
        //获取头部所有信息
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            System.out.println(key + " " + value);
        }
        // 获得 http body 内容
        BufferedReader reader = request.getReader();
        StringBuffer buffer = new StringBuffer();
        String string;
        while ((string = reader.readLine()) != null) {
            buffer.append(string);
        }
        reader.close();
        // 解析异步通知数据
        Event event = Webhooks.eventParse(buffer.toString());
        if ("charge.succeeded".equals(event.getType())) {
            PingXXRequestObjectVo pingXXRequestObjectVo = JSON.parseObject(event.getData().getObject().toString(), PingXXRequestObjectVo.class);
            OrderMain orderMain = iOrderService.getOrderMainByOrderId(Long.valueOf(pingXXRequestObjectVo.getOrder_no()));
            if (orderMain.getOrderStatus() == OrderMain.OrderStatus.WAIT_PAY.code) {
                PaySuccessRequest paySuccessRequest = new PaySuccessRequest();
                paySuccessRequest.setOrderId(Long.valueOf(pingXXRequestObjectVo.getOrder_no()));
                paySuccessRequest.setPayId(String.valueOf(pingXXRequestObjectVo.getCreated()));
                iOrderService.paySuccess(paySuccessRequest);
            }
            response.setStatus(200);
        } else if ("refund.succeeded".equals(event.getType())) {
            response.setStatus(200);
        } else {
            response.setStatus(500);
        }
    }
}